package com.itwn.comic.service;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itwn.comic.entity.Manager;
import com.itwn.comic.mapper.ManagerMapper;
import com.itwn.comic.vo.ManagerVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Repository
public class ManagerService {

    @Autowired
    ManagerMapper managerMapper ;

    public Manager queryManagerByName(String name) {

        return this.managerMapper.selectManagerByName(name);
    }

    public PageInfo<ManagerVo> queryManagerByPage(Integer now, Integer size, String name) {

        PageHelper.startPage(now , size) ;

        List<ManagerVo> list = this.managerMapper.selectManagerByPage(name) ;

        return new PageInfo<>(list) ;
    }
    @Transactional
    public void addManager(ManagerVo managerVo) {
        this.managerMapper.insertManager(managerVo) ;
        String roleIds = managerVo.getRoleIds();
        List<Integer> list = new ArrayList<>();
        for (String s :roleIds.split(",")){
            list.add(Integer.parseInt(s));
        }
        // 2.2.添加新的管理员的角色
        this.managerMapper.insertManagerAndRole(list,managerVo.getId());
    }

    
    public void removeManager(Long id) {

        this.managerMapper.deleteByPrimaryKey(id) ;
    }

    @Transactional
    public void editManager(ManagerVo managerVo) {
        //1.修改管理员信息
        this.managerMapper.updateByPrimaryKey(managerVo);
        //2.更新角色信息
        //2.1.先删除 当前管理拥有的角色
        this.managerMapper.deleteRoleByManagerId(managerVo.getId());

        String roleIds = managerVo.getRoleIds();
        List<Integer> list = new ArrayList<>();
        for (String s :roleIds.split(",")){
            list.add(Integer.parseInt(s));
        }
        // 2.2.添加新的管理员的角色
        this.managerMapper.insertManagerAndRole(list,managerVo.getId());
    }
}
